package com.ly.imgtooss.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.ly.imgtooss.config.AliyunOSSConfig;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

/**
 * @author ly
 */
@Component
public class UploadUtil {

    @Autowired
    private AliyunOSSConfig aliyunOSSConfig;

//    // 阿里域名
//    public static final String ALI_DOMAIN = "";
//    // 地域节点
//    public static final String ENDPOINT = "";
//    // 仓库名
//    public static final String BUCKET_NAME = "";
//    // 密钥ID
//    public static final String ACCESS_KEY_ID = "";
//    // 密钥密码
//    public static final String ACCESS_KEY_SECRET = "";

    /**
     * 文件上传至阿里云
     * @param file
     * @return
     * @throws IOException
     */
    public String uploadImage(MultipartFile file) throws IOException {
        // 生成文件名
        String originalFilename = file.getOriginalFilename();
        String extName = originalFilename.substring(originalFilename.lastIndexOf("."));
        String uuid = UUID.randomUUID().toString().replace("-", "");
        String fileName = uuid + extName;
        // OSS 客户端对象 （地域节点，密钥ID，密钥密码）
        OSS ossClient = new OSSClientBuilder().build(
                aliyunOSSConfig.getEndpoint(),
                aliyunOSSConfig.getAccessKeyId(),
                aliyunOSSConfig.getAccessKeySecret());

        ossClient.putObject(
                // 仓库名
                aliyunOSSConfig.getBucketName(),
                // 文件名
                fileName,
                // 文件流
                file.getInputStream()
        );
        ossClient.shutdown();
        return aliyunOSSConfig.getAliDomain() + fileName;
    }
}
